//
//  LoginViewController.m
//  DreamSoftReimburse
//
//  Created by ZJ on 17/4/12.
//  Copyright © 2017年 ZJ. All rights reserved.
//

#import "LoginViewController.h"
#import "ZJAdditions.h"
#import <SDAutoLayout.h>
#import "RegisterViewController.h"
#import "UIButton+countDown.h"
#import "NetWorkingManager.h"
#import "ZJLoginTextFieldView.h"
#import "ZJUserInfoModel.h"
#import "ZJTabBarController.h"
#import "AppDelegate.h"
#import "WelcomeView.h"
#import "LPLeftViewController.h"
#import "XLSlideMenu.h"
#import "ZJLoginJudgeManager.h"
#import "ZJReportViewController.h"
#import "ZJUserRegisterInfoModel.h"
#import "LPChooseReportTypeViewController.h"
#import "LPReportExameFailShowViewController.h"
#import "MyBranchViewController.h"
@interface LoginViewController ()
/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 手机号输入框 */
@property (nonatomic, strong) ZJLoginTextFieldView *mobelTextField;
/** 验证码输入框 */
@property (nonatomic, strong) ZJLoginTextFieldView *verification;
/** 获取验证码按钮 */
@property (nonatomic, strong) UIButton *button;
/** 登录 */
@property (nonatomic, strong) UIButton *login;
/** 注册 */
@property (nonatomic, strong) UIButton *regist;
/** 直接试用 */
@property (nonatomic, strong) UIButton *probation;

@end


@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"yindao"]) {
//        WelcomeView *welCome = [[WelcomeView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight])];
//        [self.view addSubview:welCome];
    }else{
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.leftButton.hidden = YES;
    self.titlelabel.text = @"登录";
    self.view.backgroundColor = [UIColor zj_colorWithHexString:@"ffffff"];
    [self.view addSubview:self.scrollView];
    [self setupUI];
}

- (void)setupUI{
    //公司log
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeCenter;
    imageView.image = [UIImage imageNamed:@"login_logo"];
    [self.scrollView addSubview:imageView];
    imageView.sd_layout
    .topSpaceToView(self.scrollView, 54 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .heightIs(110 * [UIScreen zj_screenHScale]);
    
    
    [self.scrollView addSubview:self.mobelTextField];
    [self.scrollView addSubview:self.verification];
    [self.scrollView addSubview:self.button];
    [self.scrollView addSubview:self.login];
    
    self.mobelTextField.sd_layout
    .leftSpaceToView(self.scrollView,27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.scrollView,27 * [UIScreen zj_screenWScale])
    .topSpaceToView(imageView, 78 * [UIScreen zj_screenHScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
  
    self.button.sd_layout
    .topSpaceToView(self.mobelTextField, 13 * [UIScreen zj_screenHScale])
    .rightEqualToView(self.mobelTextField)
    .widthIs(100 * [UIScreen zj_screenWScale])
    .heightRatioToView(self.mobelTextField, 1);
    
    self.verification.sd_layout
    .topEqualToView(self.button)
    .leftEqualToView(self.mobelTextField)
    .rightSpaceToView(self.button, 12 * [UIScreen zj_screenWScale])
    .heightRatioToView(self.button, 1);
    
    self.login.sd_layout
    .topSpaceToView(self.verification, 78 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.mobelTextField)
    .rightEqualToView(self.mobelTextField)
    .heightRatioToView(self.mobelTextField, 1);
    
    self.regist.sd_layout
    .topSpaceToView(self.login, 20 * [UIScreen zj_screenHScale])
    .centerXIs(self.view.centerX)
    .widthIs(110 * [UIScreen zj_screenWScale])
    .heightRatioToView(self.mobelTextField, 1);
    
  
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - 点击事件
/** 登录 */
- (void)action_login{
    //进行登录的网络请求
    [self userLogin];
}
/** 注册 */
-(void)action_regist{
    [self.view endEditing:YES];
    RegisterViewController * vc = [[RegisterViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}
/** 直接试用 */
- (void)action_probation{
    if (self.block) {
        self.block(NO);
    }
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isProbation"];
}
/** 发送验证码 */
- (void)action_sendVerification{
    
    if (![CManager zj_validateMobile:self.mobelTextField.textField.text]) {
 
        [YJProgressHUD showMessage:@"请输入正确的手机号码" inView:self.view afterDelayTime:2.f];
        return;
    }
    [self.verification.textField becomeFirstResponder];
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    NSDictionary *dict = @{@"MOBILE":self.mobelTextField.textField.text,@"CODE_SOURCE":@"login"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL sendVeriCode] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];

        if ([model.STATE isEqualToString:@"30000"]) {
            [YJProgressHUD hide];
            [weakSelf.button startWithTime:60 title:@"重新获取" countDownTitle:@"重新获取" mainColor:[UIColor whiteColor] countColor:[UIColor whiteColor]];
        }else{
  
            [YJProgressHUD showMessage:@"获取验证码失败" inView:weakSelf.view afterDelayTime:2.f];
        }

    } Fail:^(id object) {
        [YJProgressHUD showMessage:@"获取验证码失败" inView:weakSelf.view afterDelayTime:2.f];
    }];
}

#pragma mark - 登录的网络请求

- (void)userLogin{
    if (![CManager zj_validateMobile:self.mobelTextField.textField.text] || self.verification.textField.text.length != 6) {
        [YJProgressHUD showMessage:@"请输入正确的手机号码及验证码" inView:self.view afterDelayTime:2.f];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    NSDictionary *dict = @{@"MOBILE":self.mobelTextField.textField.text,@"CODE_SOURCE":@"login",@"MOBILE_CODE":self.verification.textField.text};
    [NetWorkingManager postWithUrlString:[NetWorkingURL login] Parameter:dict Success:^(id object) {
        [YJProgressHUD hide];
        [weakSelf judgeLoginSuccessWith:object];
    } Fail:^(id object) {
        [YJProgressHUD hide];
        [YJProgressHUD showMessage:@"登录失败" inView:weakSelf.view afterDelayTime:2.f];
    }];
}

/** 判断是否登录成功 */
- (void)judgeLoginSuccessWith:(NSDictionary *)object{
    NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
    if ([model.STATE isEqualToString:@"30000"]) {//登录成功
        [MobClick event:[UMMStatisticsString login]];
        
        [[NSUserDefaults standardUserDefaults] setObject:[object yy_modelToJSONString] forKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        [self loginJudge:object];
    }else if([model.STATE isEqualToString:@"30002"]){
        [YJProgressHUD showMessage:@"验证码错误" inView:self.view afterDelayTime:2.f];
    }else if([model.STATE isEqualToString:@"30101"]){
        [YJProgressHUD showMessage:@"手机号不存在" inView:self.view afterDelayTime:2.f];
    }else if([model.STATE isEqualToString:@"30006"]){
        [[NSUserDefaults standardUserDefaults] removeObjectForKey: USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        ZJUserRegisterInfoModel *registerModel = [ZJUserRegisterInfoModel yy_modelWithDictionary:[object objectForKey:@"ORG_ACCOUNT"]];        /**  这是该手机号未注册，自动注册 ，并且跳转选择报到页面 */
        LPChooseReportTypeViewController *vc = [LPChooseReportTypeViewController new];
        vc.registerModel = registerModel;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if([model.STATE isEqualToString:@"30001"]){
        [YJProgressHUD showMessage:@"服务器代码执行错误" inView:self.view afterDelayTime:2.f];
    }else if ([model.STATE isEqualToString:@"30009"]){
    
    
    }
}

- (void)loginJudge:(id)object{
    __weak typeof(self) weakSelf = self;
    NSString *string =  [ZJLoginJudgeManager loginJudge];
    ZJUserRegisterInfoModel *model = [ZJUserRegisterInfoModel new];
    model.ACCOUNT_ID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID : @"";
    model.MOBILE = ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE ? ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE : @"";
    model.USER_ID = ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID ? ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID : @"";
    model.PARTYMEMBER_NAME = ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME ? ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME :@"";
    if ([string isEqualToString:@"pass"]) {
        [self loginSuccess];
    }else if ([string isEqualToString:@"check"]){//跳党员报到
        ZJReportViewController *vc = [ZJReportViewController new];
        vc.registerModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([string isEqualToString:@"checkTwo"]){//需要 中间页面（组织报到、党员报到）
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        /**  这是该手机号未注册，自动注册 ，并且跳转选择报到页面 */
        LPChooseReportTypeViewController *vc = [LPChooseReportTypeViewController new];
        vc.registerModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([string isEqualToString:@"checkFail"]){//报到审核失败
        [YJProgressHUD showMessage:@"报到审核不通过" inView:[UIApplication sharedApplication].keyWindow];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        
        LPReportExameFailShowViewController *vc = [LPReportExameFailShowViewController new];
        vc.model = model;
        vc.EXAMINERESULT = [[object objectForKey:@"ORG_USER"][0] objectForKey:@"EXAMINERESULT"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [weakSelf.navigationController pushViewController:vc animated:YES];
        });
       
    }
    else if([string isEqualToString:@"login"]){//跳登录页面
      
    }else{
        [YJProgressHUD showMessage:string  inView:self.view afterDelayTime:2.f];
    }
}



- (void)loginSuccess{
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"yindao"];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
//    ZJTabBarController *zj = [[ZJTabBarController alloc] init];
//    //左侧菜单
//    LPLeftViewController *leftVC = [[LPLeftViewController alloc] init];
//    //创建滑动菜单
//    XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:zj];
//    //设置左右菜单
//    slideMenu.leftViewController = leftVC;
    MyBranchViewController *vc = [MyBranchViewController new];
    UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:vc];
    mainNav.navigationBarHidden = YES;
    [UIApplication sharedApplication].keyWindow.rootViewController =mainNav;
}

#pragma mark - Setter


#pragma mark - Getters
- (UIScrollView *)scrollView{
    if (_scrollView == nil){
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight)];
//        _scrollView.scrollEnabled = NO;
        _scrollView.contentSize = _scrollView.size;
    }
    return _scrollView;
}

- (ZJLoginTextFieldView *)mobelTextField{
    if (_mobelTextField == nil){
        _mobelTextField = [[ZJLoginTextFieldView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) imageName:@"login_con_.phone" placeholder:@"请输入手机号"];
        _mobelTextField.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _mobelTextField.maxNumber = 11;
        
    }
    return _mobelTextField;
}
- (ZJLoginTextFieldView *)verification{
    if (_verification == nil){
        _verification = [[ZJLoginTextFieldView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) imageName:@"login_con_code" placeholder:@"请输入验证码"];
        _verification.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _verification.maxNumber = 6;
    }
    return _verification;
}

- (UIButton *)button{
    if (_button == nil){
        _button = [[UIButton alloc]init];
        [_button setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _button.titleLabel.font = [UIFont systemFontOfSize:15 * [UIScreen zj_textFontScale]];
        _button.backgroundColor = [UIColor themeColor];
        _button.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        [_button addTarget:self action:@selector(action_sendVerification) forControlEvents:UIControlEventTouchUpInside];
    
    }
    return _button;
}

- (UIButton *)login{
    if (_login == nil){
        _login = [[UIButton alloc]init];
        [_login setTitle:@"登录" forState:UIControlStateNormal];
        [_login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _login.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        _login.backgroundColor = [UIColor themeColor];
        [_login addTarget:self action:@selector(action_login) forControlEvents:UIControlEventTouchUpInside];
        _login.titleLabel.font = [UIFont systemFontOfSize:15 * [UIScreen zj_textFontScale]];
    }
    return _login;
}
- (UIButton *)regist{
    if (_regist == nil){
        _regist = [[UIButton alloc]init];
        [_regist setTitle:@"用户注册" forState:UIControlStateNormal];
        [_regist setTitleColor:[UIColor textGrayColor] forState:UIControlStateNormal];
       
        [_regist addTarget:self action:@selector(action_regist) forControlEvents:UIControlEventTouchUpInside];
        _regist.titleLabel.font = [UIFont systemFontOfSize:15 * [UIScreen zj_textFontScale]];
  
    }
    return _regist;
}
- (UIButton *)probation{
    if (_probation == nil){
        _probation = [[UIButton alloc]init];
        [_probation setTitle:@"直接试用" forState:UIControlStateNormal];
        [_probation setTitleColor:[UIColor textGrayColor] forState:UIControlStateNormal];

        [_probation addTarget:self action:@selector(action_probation) forControlEvents:UIControlEventTouchUpInside];
        _probation.titleLabel.font = [UIFont systemFontOfSize:15 * [UIScreen zj_textFontScale]];
        
    }
    return _probation;
}

@end
